
package org.osami.commons.smarthome.programnotifier;

import java.io.*;
import java.net.*;

/*
 * Currently this class is unnecessary, because we are now using enigma2 web interface directly.
 * 
 */
public class EpgListener implements Runnable {
	private Thread runner;
	public static final int port = 7000;
	
	public EpgListener(String threadName) {
		runner = new Thread(this, threadName);
		runner.start();
	}
	
	public void run() {
		
		// UDP
		byte[] buf = new byte[2048];
		
		try {
			// TEST
			ProgramDatabase.getInstance().reload();
			ProgramDatabase.getInstance().print();
			// ..TEST
		
			DatagramSocket s = new DatagramSocket(port);
			System.out.println("> Java socket server waiting messages...");				
			
			while (true) {
				
				buf = new byte[2048];
	
				DatagramPacket request = new DatagramPacket(buf, buf.length);
				s.receive(request);
				String msg = new String(request.getData());//, 0, request.getLength());
				System.out.println("len = " + request.getLength() + "\n" +  msg);
										
				/*
				String msg2 = "Java says: Hello";
				byte[] b = msg2.getBytes();
				DatagramPacket d = new DatagramPacket(b, b.length);
				DatagramPacket reply = new DatagramPacket(d.getData(), d.getLength(), request.getAddress(), request.getPort());
				s.send(reply);
				*/
				
				if (msg.startsWith("EPG updated")) {
					ProgramDatabase.getInstance().reload();
					ProgramDatabase.getInstance().print();
				}
				
	    		}
		
		}
		catch (SocketException ex) {
			System.out.println("Socket: " + ex.getMessage());
		}
		catch (IOException e) {
			System.out.println("IO:" + e.getMessage());
		}
		
		
		/* TCP toteutus
		ServerSocket providerSocket = null;
		Socket connection = null;
		BufferedInputStream in = null;
		String message;
		
		try{
			providerSocket = new ServerSocket(port, 10);
			System.out.println("Waiting for connection");
			connection = providerSocket.accept();
			System.out.println("Connection received from " + connection.getInetAddress().getHostName());
			in = new BufferedInputStream(connection.getInputStream());
			while (true) {
				
				//message = in.read();
				//System.out.println("received> " + message);
				while (in.available() != 0)
					System.out.print((char)in.read());
			}
			
		}
		catch(Exception ex) {
			System.out.println("Error: " + ex.getMessage());
		}
		finally {
			try{
				in.close();
				providerSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
		*/

	}
}
